﻿using System;
using System.IO;
using System.Diagnostics;

namespace Avarton_Scanner.Logging
{
    public class Logger
    {
        //class properties
        public String LogFilePath { get; set; }

        /// <summary>
        /// Default contrustor. Also setting the filepath where the log has to be written.
        /// </summary>
        public Logger()
        {
            LogFilePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\logfile_avarton_scanner.log";
        }

        /// <summary>
        /// Method to open the logfile if any is present.
        /// </summary>
        /// <returns>Boolean to indicate a succes or fail.</returns>
        public Boolean OpenLogFile()
        {
            if (File.Exists(LogFilePath))
            {
                Process openLog = new Process();
                openLog.StartInfo.FileName = LogFilePath;
                openLog.Start();
                return true;
            }
            return false;
        }

        /// <summary>
        /// Logs a specific message to the logfile.
        /// </summary>
        /// <param name="msg">String</param>
        /// <param name="appname">String</param>
        /// <returns>Returns a bool to indicate a succes or fail.</returns>
        public bool WriteLine(String appname, String msg)
        {
            try
            {
                // Create a writer and open the file:
                StreamWriter log;

                if (!File.Exists(LogFilePath))
                {
                    log = new StreamWriter(LogFilePath);
                }
                else
                {
                    log = File.AppendText(LogFilePath);
                }

                // Write to the file:
                log.WriteLine("### {0} \t### {1} \t\t### {2} \t\t###: {3} \t\t####", DateTime.Now, appname, Environment.UserName, msg);
                

                // close the stream and flush any data containing the buffer
                log.Flush();
                log.Close();
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Unable to create a log file: " + Environment.NewLine + ex.Message);
            }
            return false;
        }

    }//end class MessageLogger
}//end namespace
